package lzyc.pointsManagement.business.userdept.controller;

import lzyc.pointsManagement.business.config.RoleEnum;
import lzyc.pointsManagement.business.userdept.domain.SysUserLogin;
import lzyc.pointsManagement.common.core.controller.BaseController;
import lzyc.pointsManagement.common.core.domain.AjaxResult;
import lzyc.pointsManagement.common.core.domain.entity.SysUser;
import lzyc.pointsManagement.common.utils.ServletUtils;
import lzyc.pointsManagement.common.utils.StringUtils;
import lzyc.pointsManagement.system.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录
 */
@Controller
@RequestMapping("/api/v1/users")
public class SysUserLoginController extends BaseController {

    @Autowired
    private ISysUserService userService;


    @GetMapping("/login")
    public String userLogin(HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
        response.setStatus(401);
        return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
    }
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxUserLogin(@RequestBody SysUserLogin sysUserLogin) {
        String username = sysUserLogin.getUsername();
        String password = sysUserLogin.getPassword();
        Boolean rememberMe = sysUserLogin.getRememberMe();
        Boolean isAdmin = sysUserLogin.getIsAdmin();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            SysUser user = userService.selectUserByLoginName(username);
            if (isAdmin && user != null && user.getUserType().equals(RoleEnum.COMMON_USER.getValue())) {
                throw new AuthenticationException();
            }
            if (!isAdmin && user != null && user.getUserType().equals(RoleEnum.ADMIN_USER.getValue())) {
                throw new AuthenticationException();
            }
            subject.login(token);
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

}